package com.ciwong.epaper.modules.homework.ui;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.PublishDKWorkHtml;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.TeaWorkDialog;
import com.ciwong.epaper.modules.homework.adapter.WorkContentFragmentAdapter;
import com.ciwong.epaper.modules.me.bean.FollowTeacher;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.zhihu.matisse.Matisse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * @description: 作业Fragment
 * @author: wyk
 * @time: 2021/9/9 16:43
 */
public class WorkFragment extends BaseFragment {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private TextView dk_work_publish;
    private TextView tea_add_work_text;

    private WorkContentFragmentAdapter adapter;
    private List<String> names;
    //关注的老师列表
    private List<FollowTeacher> followTeacherList = new ArrayList<>();

    //下划线偏移距离
    private int initMargin;
    //屏幕宽度
    private int tabLayoutWidth;

    //左边text宽度
    private int textWidth;
    //用于分辨是从哪个作业跳转过来 默认课后作业
    private String tag = RequestCode.TeaWorkContent.HOME_WORK;

    public static WorkFragment newInstance() {
        WorkFragment workFragment = new WorkFragment();
        return workFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (null != bundle) {
            tag = bundle.getString(IntentFlag.INTENT_FLAG_TAG);
        }
        initData();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_work, container, false);
        tabLayout = view.findViewById(R.id.tab_layout);
        viewPager = view.findViewById(R.id.view_pager);
        dk_work_publish = view.findViewById(R.id.dk_work_publish);
        tea_add_work_text = view.findViewById(R.id.tea_add_work_text);
        //ButterKnife.bind(this, view);

        adapter = new WorkContentFragmentAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        // 更新适配器数据
        adapter.setList(names);
        //TabLayoutUtil.reflex(tabLayout);
        viewPager.setOffscreenPageLimit(adapter.getCount());
        init();
        setView();
        if (null != tag) {
            switch (tag) {
                case RequestCode.TeaWorkContent.HOME_WORK:
                    viewPager.setCurrentItem(0);
                    break;
                case RequestCode.TeaWorkContent.COMPUTER_ROOM_EXAM:
                    viewPager.setCurrentItem(1);
                    break;
                case RequestCode.TeaWorkContent.CLASS_WORK:
                    viewPager.setCurrentItem(2);
                    break;
                case RequestCode.TeaWorkContent.DK_WORK:
                    viewPager.setCurrentItem(3);
                    break;
                default:
                    viewPager.setCurrentItem(0);

            }
        }
        return view;
    }


    private void initData() {
        names = new ArrayList<>();
        names.add(getResources().getString(R.string.home_work_mode));
        names.add(getResources().getString(R.string.computer_room_exam));
        names.add(getResources().getString(R.string.class_work_mode));
        names.add(getResources().getString(R.string.dk_work));
        getFollowTeachers();
    }

    private List<String> subImgPathList = new ArrayList<>();

    /**
     * 设置下划线位置 及选中标题放大加粗效果
     */
    public void setView() {

        //第一次先设置下划线默认位置
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //如果有CustomView 先清除再添加 避免重复
                    TabLayout.Tab tabAt = tabLayout.getTabAt(tabLayout.getSelectedTabPosition());
                    View view = tabAt.getCustomView();
                    if (null != view) {
                        tabAt.setCustomView(null);
                    }
                    tabAt.setCustomView(R.layout.custrom_tab);
                    TextView textView = tabAt.getCustomView().findViewById(R.id.t_tab);
                    //获取默认选中Tab

                    //获取标题
                    String title = tabAt.getText().toString().trim();
                    SpannableString spannableString = new SpannableString(title);
                    //设置字号
                    AbsoluteSizeSpan span = new AbsoluteSizeSpan(DisplayUtils.sp2px(getContext(), 17));
                    //设置颜色
                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(getActivity().getResources().getColor(R.color.white));

                    StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);

                    spannableString.setSpan(span, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    spannableString.setSpan(colorSpan, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    spannableString.setSpan(styleSpan, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    textView.setText(spannableString);

                } catch (Exception e) {
                }

            }
        });


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //如果有CustomView 先清除再添加 避免重复
                View view = tab.getCustomView();
                if (null != view) {
                    tab.setCustomView(null);
                }
                tab.setCustomView(R.layout.custrom_tab);
                TextView textView = tab.getCustomView().findViewById(R.id.t_tab);
                //获取标题
                String title = tab.getText().toString().trim();
                SpannableString spannableString = new SpannableString(title);
                //设置字号
                AbsoluteSizeSpan span = new AbsoluteSizeSpan(DisplayUtils.sp2px(getContext(), 17));
                //设置颜色
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(getActivity().getResources().getColor(R.color.white));

                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);

                spannableString.setSpan(span, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString.setSpan(colorSpan, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString.setSpan(styleSpan, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                textView.setText(spannableString);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (null == tab || null == tab.getText()) {
                    return;
                }
                String title = tab.getText().toString().trim();
                SpannableString spannableString = new SpannableString(title);
                //设置颜色
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(getActivity().getResources().getColor(R.color.white));
                //设置字号
                AbsoluteSizeSpan span = new AbsoluteSizeSpan(DisplayUtils.sp2px(getContext(), 15));
                spannableString.setSpan(span, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString.setSpan(colorSpan, 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                tab.setText(spannableString);
                tab.setCustomView(null);

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void init() {
        dk_work_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //EpaperJumpManager.jumpToPublishDKWorkHtml(R.id.go_back,mActivity);
                showPublishDKDialog(dk_work_publish);
            }
        });

        tea_add_work_text.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                int currentItem = viewPager.getCurrentItem();
                //按列表点击+号布置 到布置最后一步默认该模式 打卡作业列表点击加号到打卡作业布置页面
                if (currentItem == 3) {
                    //跳转至发布打卡作业页面
                    EpaperJumpManager.jumpToPublishDKWorkHtml(R.id.go_back, getActivity());
                } else {
                    //默认为课后作业模式
                    String itemTag = RequestCode.TeaWorkContent.HOME_WORK;
                    int item = viewPager.getCurrentItem();
                    switch (item) {
                        case 0:
                            itemTag = RequestCode.TeaWorkContent.HOME_WORK;
                            break;
                        case 1:
                            itemTag = RequestCode.TeaWorkContent.COMPUTER_ROOM_EXAM;
                            break;
                        case 2:
                            itemTag = RequestCode.TeaWorkContent.CLASS_WORK;
                            break;
                        default:
                            itemTag = RequestCode.TeaWorkContent.HOME_WORK;
                            break;
                    }
                    //跳转至收藏书籍页面
                    MeJumpManager.jumpToFavoritesListActivity(mActivity, itemTag, R.string.go_back);
                }

            }
        });
    }

    /**
     * 显示发布打卡作业弹框
     *
     * @param textView
     */
    public void showPublishDKDialog(TextView textView) {
        View workHintDialogView = LayoutInflater.from(mActivity).inflate(R.layout.activity_publish_dk_work_dialog, null);
        final int 锚点坐标[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        textView.getLocationOnScreen(锚点坐标);
        int 锚点宽度 = textView.getWidth();
        int 锚点高度 = textView.getHeight();
        //偏移量 = 屏幕的一半 - 弹窗的一半 - 锚点的一半 - 边距
        int 屏幕宽度 = DisplayUtils.getScreenWidth(mActivity);
        int 屏幕高度 = DisplayUtils.getScreenHeight(mActivity);
        workHintDialogView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int 弹窗宽度 = workHintDialogView.getMeasuredWidth() / 2;
        int 弹窗高度 = workHintDialogView.getMeasuredHeight();
        int X轴的偏移量 = (屏幕宽度 / 2 - 弹窗宽度 / 2 - (屏幕宽度 - 锚点坐标[0]) + 锚点宽度 / 2);//右边便宜要加上锚点的一半和右边的边距。
        int Y轴的偏移量 = -(屏幕高度 / 2 - 弹窗高度 / 2 - 锚点坐标[1] + DisplayUtils.getStatusBarHeight(mActivity) / 2 - 锚点高度);
        CWLog.i("X轴的偏移量", +X轴的偏移量 + "");
        CWLog.i("Y轴的偏移量", +Y轴的偏移量 + "");
        final TeaWorkDialog homeWorkHintDialog = new TeaWorkDialog(mActivity, workHintDialogView, X轴的偏移量, Y轴的偏移量, 屏幕宽度, true);
        LinearLayout attention_work_lay = workHintDialogView.findViewById(R.id.attention_work_lay);
        LinearLayout publish_dk_work_lay = workHintDialogView.findViewById(R.id.publish_dk_work_lay);
        if (null != followTeacherList && followTeacherList.size() > 0) {
            attention_work_lay.setVisibility(View.VISIBLE);
            attention_work_lay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    EpaperJumpManager.jumpToAttentionWork(R.id.go_back, mActivity,followTeacherList);
                    homeWorkHintDialog.dismiss();
                }
            });
        } else {
            attention_work_lay.setVisibility(View.GONE);
        }
        publish_dk_work_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EpaperJumpManager.jumpToPublishDKWorkHtml(R.id.go_back, mActivity);
                homeWorkHintDialog.dismiss();
            }
        });


        homeWorkHintDialog.show();
    }

    /**
     * 获取关注老师列表
     */
    private void getFollowTeachers() {
        EpaperDao.getInstance().getFollowTeachers(EApplication.BRAND_ID, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                }
            }

            @Override
            public void success(Object data) {
                if (null != data) {
                    followTeacherList = (List<FollowTeacher>) data;
                    if (null == followTeacherList || followTeacherList.size() == 0) {
                        dk_work_publish.setVisibility(View.INVISIBLE);
                    } else {
                        dk_work_publish.setVisibility(View.VISIBLE);
                    }
                    //setView();
                }
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mRequestCode = requestCode;
        mResultCode = resultCode;
        if (resultCode == RESULT_OK) {
            if (requestCode == PublishDKWorkHtml.REQUEST_CODE_ALBUM) {
                PhotoResult = Matisse.obtainResult(data);
                for (int i = 0; i < PhotoResult.size(); i++) {
                    Uri path = PhotoResult.get(i);
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getActivity().getContentResolver().query(path,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    subImgPathList.add(cursor.getString(columnIndex));
                    //submitPic(subImgPath);
                    cursor.close();
                }
                data.putExtra(IntentFlag.INTENT_FLAG_PHOTO_LIST, (Serializable) subImgPathList);
                adapter.getItem(1).onActivityResult(mRequestCode, mResultCode, data);
                //adapter.getItem(1).onActivityResult(mRequestCode,mResultCode,data);
            }
        }

    }

    //从相册选择照片集合
    List<Uri> PhotoResult = new ArrayList<>();
    private int mRequestCode;
    private int mResultCode;


    @Override
    public void onDestroy() {
        //ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
        super.onDestroy();
    }
}
